#include <sys_head.h>

void file_copy(int fd_dest,int fd_src);

int main(int argc, char const *argv[])
{
    if (argc < 3)
    {
        printf("格式错误: %s 目标文件 源文件\n",argv[0]);
        return 0;
    }
    int fd_dest = open(argv[1] , O_CREAT | O_RDWR | O_TRUNC , 0666);
    if (fd_dest == -1)
    {
        perror("open");
        return 0;
    }
    
    for (size_t i = 2; i < argc; i++)
    {
        int fd_src = open(argv[i] , O_RDONLY , 0666);
        if (fd_src == EOF )
        {
            ERRLOG("open");
            return 0;
        }
        file_copy(fd_dest,fd_src);
        //关闭文件
        close(fd_src);
        
    }
    close(fd_dest);
    return 0;
}

void file_copy(int fd_dest,int fd_src)
{
    char buf[1024];
    ssize_t bytesRead;  
    while ((bytesRead = read(fd_src, buf, sizeof(buf))) > 0) {  
        if (write(fd_dest, buf, bytesRead) != bytesRead) {  
            ERRLOG("write");  
        }  
    }  
    if (bytesRead == -1) {  
        ERRLOG("read");  
    }  
}